package com.byzk.p2p.admin.money.controller;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.byzk.p2p.admin.base.controller.AdminBaseController;
import com.byzk.p2p.admin.base.util.DateUtils;
import com.byzk.p2p.admin.base.util.JsonMsg;
import com.byzk.p2p.admin.base.util.PageInfo;
import com.byzk.p2p.admin.borrow.dto.Borrow;
import com.byzk.p2p.admin.borrow.dto.BorrowApply;
import com.byzk.p2p.admin.borrow.service.BorrowService;
import com.byzk.p2p.admin.borrow.vo.BorrowTempVo;
import com.byzk.p2p.admin.money.service.BorrowPaymentDetailService;
import com.byzk.p2p.admin.money.service.BorrowPaymentService;
import com.byzk.p2p.admin.money.service.RechargeService;
import com.byzk.p2p.admin.money.vo.BorrowPaymentDetailVo;
import com.byzk.p2p.admin.money.vo.BorrowPaymentVo;
import com.byzk.p2p.admin.user.dto.UserAccount;
import com.byzk.p2p.admin.user.service.UserAccountService;

/**
 * 借款人还款Controller
 * 
 * @author suker.zhou
 *
 */
@Controller
@RequestMapping("/admin/borrowPayment")
public class BorrowPaymentController extends AdminBaseController {

	@Autowired
	private BorrowPaymentService borrowPaymentService;
	@Autowired
	private BorrowPaymentDetailService borrowPaymentDetailService;
	@Autowired
	private BorrowService borrowService;
	@Autowired
	private UserAccountService userAccountService;
	@Autowired
	private RechargeService rechargeService;
	
	/**
	 * 借款人逾期还款记录
	 * @param model
	 * @param index
	 * @param limit
	 * @param expectDateBegin 理论还款时间，开始
	 * @param expectDateEnd 理论还款时间，结束
	 * @param actualDateBegin 实际还款时间，开始
	 * @param actualDateEnd 实际还款时间，结束
	 * @return
	 */
	@RequestMapping("/listOverdue")
	public String listOverdueBorrowPayment(Model model,
										@ModelAttribute BorrowPaymentVo vo,
										@RequestParam(value="overdueDay",required=false,defaultValue="-1") int overdueDay,
										@RequestParam(value="expectDateBegin",required=false)String expectDateBegin,
									    @RequestParam(value="expectDateEnd",required=false)String expectDateEnd,
									    @RequestParam(value="actualDateBegin",required=false)String actualDateBegin,
									    @RequestParam(value="actualDateEnd",required=false)String actualDateEnd)throws Exception {
		vo.setOverdueDay(overdueDay);
		if (StringUtils.isNotBlank(expectDateBegin)) {
			vo.setExpectPaymentDateBegin(DateUtils.getRealDate(DateUtils.convert(expectDateBegin, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
			model.addAttribute("expectPaymentDateBegin", expectDateBegin);
		}
		if (StringUtils.isNotBlank(expectDateEnd)) {
			vo.setExpectPaymentDateEnd(DateUtils.getFullDate(DateUtils.convert(expectDateEnd, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
			model.addAttribute("expectPaymentDateEnd", expectDateEnd);
		}
		if (StringUtils.isNotBlank(actualDateBegin)) {
			vo.setActualPaymentDateBegin(DateUtils.getRealDate(DateUtils.convert(actualDateBegin, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
			model.addAttribute("actualPaymentDateBegin", actualDateBegin);
		}
		if (StringUtils.isNotBlank(actualDateEnd)) {
			vo.setActualPaymentDateEnd(DateUtils.getFullDate(DateUtils.convert(actualDateEnd, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
			model.addAttribute("actualPaymentDateEnd", actualDateEnd);
		}
		PageInfo<BorrowPaymentVo> pageInfo = getBorrowPaymentPageInfo(vo);
		model.addAttribute("pageInfo", pageInfo);
		return ftl(Thread.currentThread().getStackTrace());
	}
	
	/**
	 * 所有借款人还款记录
	 * @param model
	 * @param vo
	 * @return
	 */
	@RequestMapping("/list")
	public String listBorrowPayment(Model model,@ModelAttribute BorrowPaymentVo vo) {
		PageInfo<BorrowPaymentVo> pageInfo = getBorrowPaymentPageInfo(vo);
		model.addAttribute("pageInfo", pageInfo);
		return ftl(Thread.currentThread().getStackTrace());
	}

	/**
	 * 借款标还款列表
	 * @param model
	 * @param index
	 * @param limit
	 * @param status 借款标状态
	 * @param expectDateBegin 理论还款时间，开始
	 * @param expectDateEnd 理论还款时间，结束
	 * @param actualDateBegin 实际还款时间，开始
	 * @param actualDateEnd 实际还款时间，结束
	 * @param matchTitle 借款标题
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/listBorrowRepay")
	public String listBorrowRepay(Model model,
					@ModelAttribute BorrowTempVo vo,
					@RequestParam(value="expectDateBegin",required=false)String expectDateBegin,
				    @RequestParam(value="expectDateEnd",required=false)String expectDateEnd,
				    @RequestParam(value="actualDateBegin",required=false)String actualDateBegin,
				    @RequestParam(value="actualDateEnd",required=false)String actualDateEnd)throws Exception {
/*		if (StringUtils.isNotBlank(vo.getStatus())) {
			model.addAttribute("status", vo.getStatus());
		}
		if (StringUtils.isNotBlank(expectDateBegin)) {
			vo.setExpectPaymentDateBegin(expectDateBegin);
			model.addAttribute("expectPaymentDateBegin", expectDateBegin);
		}
		if (StringUtils.isNotBlank(expectDateEnd)) {
			vo.setExpectPaymentDateEnd(expectDateEnd);
			model.addAttribute("expectPaymentDateEnd", expectDateEnd);
		}*/
		if (StringUtils.isNotBlank(actualDateBegin)) {
			vo.setActualPaymentDateBegin(DateUtils.getRealDate(DateUtils.convert(actualDateBegin, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
			model.addAttribute("actualPaymentDateBegin", actualDateBegin);
		}
		if (StringUtils.isNotBlank(actualDateEnd)) {
			vo.setActualPaymentDateEnd(DateUtils.getFullDate(DateUtils.convert(actualDateEnd, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
			model.addAttribute("actualPaymentDateEnd", actualDateEnd);
		}
		if (StringUtils.isNotBlank(vo.getMatchTitle())) {
			model.addAttribute("matchTitle", vo.getMatchTitle());
		}
		vo.setStatus("complete");
		PageInfo<BorrowTempVo> pageInfo = borrowService.getBorrowRepay(vo);
		//List<BorrowPaymentDetail> detailList = borrowPaymentService.getDetailsByBorrow(vo);
		model.addAttribute("pageInfo", pageInfo);
		//model.addAttribute("detailList", detailList);
		return ftl(Thread.currentThread().getStackTrace());
	}
	
	/**
	 * 未还完还款
	 * @param model
	 * @param index
	 * @param limit
	 * @param expectDateBegin 理论还款时间，开始
	 * @param expectDateEnd 理论还款时间，结束
	 * @param actualDateBegin 实际还款时间，开始
	 * @param actualDateEnd 实际还款时间，结束
	 * @param matchTitle 借款标题
	 * @return
	 */
	@RequestMapping("/listUnReturnBorrowPayment")
	public String listUnReturnBorrowPayment(Model model,
								@ModelAttribute BorrowPaymentVo vo,
								@RequestParam(value="expectDateBegin",required=false)String expectDateBegin,
							    @RequestParam(value="expectDateEnd",required=false)String expectDateEnd,
							    @RequestParam(value="actualDateBegin",required=false)String actualDateBegin,
							    @RequestParam(value="actualDateEnd",required=false)String actualDateEnd)throws Exception {
		vo.setStatus("N");
		vo.setBorrowStatus("pay");
		if (StringUtils.isNotBlank(expectDateBegin)) {
			vo.setExpectPaymentDateBegin(DateUtils.getRealDate(DateUtils.convert(expectDateBegin, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
			model.addAttribute("expectPaymentDateBegin", expectDateBegin);
		}
		if (StringUtils.isNotBlank(expectDateEnd)) {
			vo.setExpectPaymentDateEnd(DateUtils.getFullDate(DateUtils.convert(expectDateEnd, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
			model.addAttribute("expectPaymentDateEnd", expectDateEnd);
		}
		if (StringUtils.isNotBlank(actualDateBegin)) {
			vo.setActualPaymentDateBegin(DateUtils.getRealDate(DateUtils.convert(actualDateBegin, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
			model.addAttribute("actualPaymentDateBegin", actualDateBegin);
		}
		if (StringUtils.isNotBlank(actualDateEnd)) {
			vo.setActualPaymentDateEnd(DateUtils.getFullDate(DateUtils.convert(actualDateEnd, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
			model.addAttribute("actualPaymentDateEnd", actualDateEnd);
		}
		if (StringUtils.isNotBlank(vo.getMatchTitle())) {
			model.addAttribute("matchTitle", vo.getMatchTitle());
		}
		PageInfo<BorrowPaymentVo> pageInfo = getBorrowPaymentPageInfo(vo);
		model.addAttribute("pageInfo", pageInfo);
		return ftl(Thread.currentThread().getStackTrace());
	}
	
	/**
	 * 借款标每一期的还款详细
	 * @param model
	 * @param paymentId 借款还款id
	 * @return
	 */
	@RequestMapping("/listBorrowPaymentDetail")
	public String listBorrowPaymentDetail(Model model,@RequestParam Integer paymentId,
			@RequestParam(value="index",required=false,defaultValue="1") int index,
			@RequestParam(value="limit",required=false,defaultValue="10") int limit){
		BorrowPaymentDetailVo detailVo = new BorrowPaymentDetailVo();
		detailVo.setPaymentId(paymentId);
		detailVo.setIndex(index);
		//TODO 还款详情不分页
		detailVo.setLimit(99999);
		PageInfo<BorrowPaymentDetailVo> pageInfo = borrowPaymentDetailService.list(detailVo);
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("paymentId", paymentId);
		return ftl(Thread.currentThread().getStackTrace());
	}
	
	/**
	 * 借款标还款明细
	 * @param model
	 * @param borrowId 借款标id
	 * @return
	 */
	@RequestMapping("/listBorrowPayment")
	public String listBorrowPayment(Model model,@RequestParam Integer borrowId,
			@RequestParam(value="index",required=false,defaultValue="1") int index,
			@RequestParam(value="limit",required=false,defaultValue="10") int limit){
		Borrow borrow = borrowService.getBorrowById(borrowId);
		BorrowPaymentVo detailVo = new BorrowPaymentVo();
		detailVo.setBorrowId(borrowId);
		detailVo.setBorrowStatus(borrow.getStatus());
		detailVo.setIndex(index);
		//TODO 还款列表不分页
		detailVo.setLimit(99999);
		PageInfo<BorrowPaymentVo> pageInfo = borrowPaymentService.list(detailVo);
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("borrowId", borrowId);
		return ftl(Thread.currentThread().getStackTrace());
	}
	
	/**
	 * 还款
	 * @param pid 还款记录id
	 * @param borrowId 借款标id
	 * @return
	 */
	@RequestMapping(value = "/payment", method = RequestMethod.POST)
	public void payment(@RequestParam("pid") Integer pid,
						@RequestParam("borrowId") Integer borrowId) throws Exception {
		try {
			Borrow borrow = borrowService.getBorrowById(borrowId);
			if (borrow == null) {
				printJSON(new JsonMsg(1, "借款标获取失败"));
				return;
			}
			if (borrow.getBorrowApplyId().equals(-1)) {
				BorrowPaymentVo borrowPaymentVo = new BorrowPaymentVo();
				borrowPaymentVo.setBorrowId(borrowId);
				List<BorrowPaymentVo> paymentVos = borrowPaymentService.borrowUserRepayList(borrowPaymentVo);
				if (paymentVos == null || paymentVos.size() == 0 || paymentVos.size() >1) {
					printJSON(new JsonMsg(2, "还款失败，数据异常！"));
					return;
				}
				BorrowPaymentVo paymentVo = paymentVos.get(0);
				Integer i = borrowPaymentService.payment(paymentVo.getId());
				if (i >0) {
					printJSON(new JsonMsg(-1, "还款成功！"));
					return;
				}else{
					printJSON(new JsonMsg(3, "还款失败！"));
					return;
				}
			}else{
				BorrowApply borrowApply = borrowService.getBorrowApply(borrow.getBorrowApplyId());
				if (borrowApply == null) {
					printJSON(new JsonMsg(4, "借款用户获取失败"));
					return;
				}
				UserAccount userAccount = userAccountService.getByUserId(borrowApply.getUserId());
				BorrowPaymentVo borrowPaymentVo = borrowPaymentService.detail(pid);
				if (userAccount == null || borrowPaymentVo == null || userAccount.getBalance() == null
						|| userAccount.getBalance() <= 0d
						|| userAccount.getBalance() < borrowPaymentVo.getNotPaymentTotal()) {
					//printJSON(new JsonMsg(5, "还款失败！用户可用余额不足！"));
					//余额不足，自动充值
					rechargeService.autoRecharge(userAccount.getUserId(),borrowPaymentVo.getNotPaymentTotal());
					
				}
				if(borrowPaymentService.checkPayment(borrowId,borrowApply.getUserId(),borrowPaymentVo.getPeriodIndex())){
					Integer i = borrowPaymentService.payment(pid);
					if (i > 0) {
						printJSON(new JsonMsg(-1, "还款成功！"));
						return;
					}else{
						printJSON(new JsonMsg(6, "还款失败！"));
						return;
					}
				}else{
					printJSON(new JsonMsg(7, "请按照期数依次还款！"));
					return;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private PageInfo<BorrowPaymentVo> getBorrowPaymentPageInfo(BorrowPaymentVo vo){
		PageInfo<BorrowPaymentVo> pageInfo = borrowPaymentService.list(vo);
		return pageInfo;
	}
}
